from aiofiles import open as aiofiles_open
from argparse import ArgumentParser
from fastapi import FastAPI, File, UploadFile, Response
from os import makedirs
from os.path import exists
from uuid import uuid1

parser = ArgumentParser()
parser.add_argument('--hostname', type=str, default='https://ljjkj.com')
parser.add_argument('--directory', type=str, default='/home/leo/fastdfs/storage')
parser.add_argument('--port', type=int, default=9000)
config = parser.parse_args()

server = FastAPI(directory=config.directory)

@server.get('/fastdfs/images/{filename}.{ext}')
async def get_image(filename: str, ext: str):
    path = f'{config.directory}/image/{ext}/{filename}.{ext}'
    if not exists(path):
        return {'error': 'file not found'}
    async with aiofiles_open(path, 'rb') as f:
        content = await f.read()
        return Response(content=content, media_type=f'image/{ext}')

@server.post('/fastdfs/upload')
async def upload(file: UploadFile = File(...)):
    name = uuid1().hex + '.' + file.content_type.split('/')[-1]
    path = f'{config.directory}/{file.content_type}'
    if not exists(path):
        makedirs(path)
    buff = await file.read()
    path = f'{path}/{name}'
    async with aiofiles_open(path, 'wb') as f:
        await f.write(buff)
    return {
        'errno': 0,
        'data': {
            'url': f'{config.hostname}/fastdfs/images/{name}'
        }
    }


def main():
    import uvicorn

    uvicorn.run(app='main:server', host='0.0.0.0', port=config.port, reload=True)


if __name__ == '__main__':
    main()